#!groovy
import groovy.json.JsonOutput
import groovy.json.JsonSlurper


node ("sftp-artifacts"){
    def sftpUrl = params.sftpUrl
    def app = params.app
    def packageName = params.packageName
    def packageType = params.packageType
    try{
        println("App :"+ app)
        wrap([$class: 'MaskPasswordsBuildWrapper',
              varPasswordPairs: [[password: "${params.sftpUser}", var: 'sftpUser'],
                                 [password: "${params.sftpPwd}", var: 'sftpPwd'],
                                 [password: "${params.releasePwd}", var: 'releasePwd']]]){
            def appTags = tagsFromSftp(app,packageName,sftpUrl,packageType)
            sleep 1
            //SFTP获取TAG列表
            notifyDeployCentral(30003,appTags)
        }
    }catch (e){
        echo 'Pull Artifact error !'
        //SFTP获取TAG列表
        notifyDeployCentral(30004,"")
        throw exc
    }
}

def tagsFromSftp(app,packageName,sftpUrl,packageType){
    stage('Pull Artifact From SFTP') {
        echo " Pull Artifact ${app}-${packageName}.${packageType} "
        def appTags = "";
        script{
            withEnv(['JENKINS_NODE_COOKIE=dontkillme']) {
             sh """
                lftp -u ${params.sftpUser},${params.sftpPwd} $sftpUrl <<EOF
                ls file/${app}/ > ${app}_tags.txt
                exit
                EOF
             """
             sh "cat ${app}_tags.txt | awk '{print \$9}' | grep -v '\\.'| sort -r > ${app}_tags_ex.txt"
             readFile("${app}_tags_ex.txt").split("\r?\n").each {
                 appTags = appTags + it + ","
             }
             sh "rm -rf ${app}_tags_ex.txt ${app}_tags.txt"
             appTags = appTags.substring(0,(appTags.length()-1));
             println appTags;
            }
        }
        return appTags;
    }
}

def notifyDeployCentral(status,appTags){
    stage("Notify DeployCentral"){
        echo "Notify DeployCentral: "+status
        def response = httpRequest(url:"${params.callBackHost}/deploy-central/prod/jenkins/notify?callBackId=${params.callBackId}&status=${status}&buildId=${BUILD_ID}&action=${JOB_NAME}@${appTags}",timeout: 10)
        println('Status: '+response.status)
    }
}